﻿
// NetEngine_WINAptAppDlg.cpp: 实现文件
//

#include "stdafx.h"
#include "NetEngine_WINAptApp.h"
#include "NetEngine_WINAptAppDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CNetEngineWINAptAppDlg 对话框



CNetEngineWINAptAppDlg::CNetEngineWINAptAppDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_NETENGINE_WINAPTAPP_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CNetEngineWINAptAppDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST2, m_ListRecord);
	DDX_Control(pDX, IDC_EDIT1, m_EditModuleName);
	DDX_Control(pDX, IDC_STATIC_TIPS, m_StaticTips);
	DDX_Control(pDX, IDC_RADIO1, m_RadioLocal);
	DDX_Control(pDX, IDC_RADIO2, m_RadioRemote);
}

BEGIN_MESSAGE_MAP(CNetEngineWINAptAppDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, &CNetEngineWINAptAppDlg::OnBnClickedButton1)
	ON_WM_SIZE()
	ON_WM_DESTROY()
	ON_NOTIFY(NM_RCLICK, IDC_LIST2, &CNetEngineWINAptAppDlg::OnNMRClickList2)
	ON_UPDATE_COMMAND_UI(ID_32775, &CNetEngineWINAptAppDlg::OnUpdate32775)
	ON_UPDATE_COMMAND_UI(ID_32774, &CNetEngineWINAptAppDlg::OnUpdate32774)
	ON_BN_CLICKED(IDC_RADIO1, &CNetEngineWINAptAppDlg::OnBnClickedRadio1)
	ON_BN_CLICKED(IDC_RADIO2, &CNetEngineWINAptAppDlg::OnBnClickedRadio2)
END_MESSAGE_MAP()

BEGIN_EASYSIZE_MAP(CNetEngineWINAptAppDlg)
	EASYSIZE(IDC_STATIC_SEARCH, ES_BORDER, ES_BORDER, ES_KEEPSIZE, ES_KEEPSIZE, 0)
	EASYSIZE(IDC_STATIC_CONFIG, ES_BORDER, ES_BORDER, ES_KEEPSIZE, ES_KEEPSIZE, 0)
	EASYSIZE(IDC_STATIC_NAME, ES_BORDER, ES_BORDER, ES_BORDER, ES_KEEPSIZE, 0)
	EASYSIZE(IDC_EDIT1, ES_BORDER, ES_BORDER, ES_KEEPSIZE, ES_KEEPSIZE, 0)
	EASYSIZE(IDC_BUTTON1, ES_BORDER, ES_BORDER, ES_KEEPSIZE, ES_KEEPSIZE, 0)

	EASYSIZE(IDC_STATIC_TIPS, ES_BORDER, ES_KEEPSIZE, ES_KEEPSIZE, ES_BORDER, 0)
	EASYSIZE(IDC_STATIC_RECORD, ES_BORDER, ES_BORDER, ES_BORDER, IDC_STATIC_TIPS, 0)
	EASYSIZE(IDC_LIST2, ES_BORDER, ES_BORDER, ES_BORDER, IDC_STATIC_TIPS, 0)
END_EASYSIZE_MAP
// CNetEngineWINAptAppDlg 消息处理程序

BOOL CNetEngineWINAptAppDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	WSADATA st_WSAData;
	WSAStartup(MAKEWORD(2, 2), &st_WSAData);
	// TODO: 在此添加额外的初始化代码
	bIsRun = TRUE;
	InitializeCriticalSection(&st_Locker);

	m_ListRecord.InsertColumn(0, _T("编号"), LVCFMT_CENTER, 60);
	m_ListRecord.InsertColumn(1, _T("名称"), LVCFMT_CENTER, 100);
	m_ListRecord.InsertColumn(2, _T("全称"), LVCFMT_CENTER, 200);
	m_ListRecord.InsertColumn(3, _T("版本"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(4, _T("作者"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(5, _T("提供者"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(6, _T("构建日期"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(7, _T("联系方式"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(8, _T("项目主页"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(9, _T("运行架构"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(10, _T("下载大小"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(11, _T("安装大小"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(12, _T("下载地址"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(13, _T("文件MD5"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(14, _T("依赖组件"), LVCFMT_CENTER, 80);
	m_ListRecord.InsertColumn(15, _T("描述信息"), LVCFMT_CENTER, 80);
	m_ListRecord.SetExtendedStyle(LVS_EX_FULLROWSELECT);
	m_RadioRemote.SetCheck(BST_CHECKED);
	INIT_EASYSIZE;

	CMenu m_Menu;
	m_Menu.LoadMenu(IDR_MENU1);
	SetMenu(&m_Menu);
	m_Menu.Detach();

	m_StaticTips.SetWindowText(_T("提示信息:"));

	WINApt_ReadConfig();
	if (!DataBase_SQLite_Create(st_AppConfig.st_CfgFile.tszDBFile))
	{
		if (ERROR_HELPCOMPONENTS_DATABASE_SQLITE_CREATE_ISEXIST != DataBase_GetLastError())
		{
			AfxMessageBox(_T("创建数据库文件失败"));
			return FALSE;
		}
	}
	if (!DataBase_SQLite_Open(&xhDBFile, st_AppConfig.st_CfgFile.tszDBFile))
	{
		AfxMessageBox(_T("打开数据库文件失败"));
		return FALSE;
	}

	hThread = CreateThread(NULL, 0, WINApt_Thread_Download, this, 0, NULL);
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CNetEngineWINAptAppDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CNetEngineWINAptAppDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CNetEngineWINAptAppDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	int nMsgLen = 0;
	CString m_StrModuleName;
	TCHAR tszMsgBuffer[2048];

	memset(tszMsgBuffer, '\0', sizeof(tszMsgBuffer));
	m_EditModuleName.GetWindowText(m_StrModuleName);

	if (m_StrModuleName.IsEmpty())
	{
		AfxMessageBox(_T("查询内容不能为空"));
		return;
	}

	if (BST_CHECKED == m_RadioLocal.GetCheck())
	{
		WINApt_ProtocolPkt_SearchRequest(m_StrModuleName.GetBuffer(), tszMsgBuffer, &nMsgLen);
		WINApt_SendPktMsg(tszMsgBuffer, nMsgLen);
	}
	if (BST_CHECKED == m_RadioRemote.GetCheck())
	{
		WINApt_ProtocolPkt_SearchRequest(m_StrModuleName.GetBuffer(), tszMsgBuffer, &nMsgLen);
		WINApt_SendPktMsg(tszMsgBuffer, nMsgLen);
	}
}


void CNetEngineWINAptAppDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialogEx::OnSize(nType, cx, cy);

	// TODO: 在此处添加消息处理程序代码
	UPDATE_EASYSIZE;
}


void CNetEngineWINAptAppDlg::OnDestroy()
{
	CDialogEx::OnDestroy();

	// TODO: 在此处添加消息处理程序代码
	bIsRun = FALSE;
	CloseHandle(hThread);
	DeleteCriticalSection(&st_Locker);
	WSACleanup();
}
BOOL CNetEngineWINAptAppDlg::WINApt_SendPktMsg(LPCTSTR lpszMsgBuffer, int nMsgLen)
{
	int nRecvLen = 2048;
	SOCKET m_Socket = INVALID_SOCKET;
	TCHAR tszMsgBuffer[2048];

	memset(tszMsgBuffer, '\0', sizeof(tszMsgBuffer));

	if (!NetClient_TCPSelect_Create(st_AppConfig.st_CfgNetWork.tszIPAddr, st_AppConfig.st_CfgNetWork.nPort, &m_Socket))
	{
		AfxMessageBox(_T("无法连接到服务器"));
		return FALSE;
	}
	if (!NetClient_TCPSelect_SendMsg(m_Socket, lpszMsgBuffer, nMsgLen))
	{
		AfxMessageBox(_T("无法发送数据"));
		NetClient_TCPSelect_Close(m_Socket);
		return FALSE;
	}
	if (!NetClient_TCPSelect_RecvMsg(m_Socket, tszMsgBuffer, &nRecvLen,FALSE))
	{
		AfxMessageBox(_T("无法接受数据"));
		NetClient_TCPSelect_Close(m_Socket);
		return FALSE;
	}
	NetClient_TCPSelect_Close(m_Socket);
	NETENGINE_PROTOCOLHDR st_ProtocolHdr;
	memset(&st_ProtocolHdr, '\0', sizeof(NETENGINE_PROTOCOLHDR));
	memcpy(&st_ProtocolHdr, tszMsgBuffer, sizeof(NETENGINE_PROTOCOLHDR));

	WINApt_ParseListLoad(tszMsgBuffer + sizeof(NETENGINE_PROTOCOLHDR));
	return TRUE;
}
BOOL CNetEngineWINAptAppDlg::WINApt_ReadConfig()
{
	LPCTSTR lpszCfgFile = _T("E:\\NetEngine_WINApt\\Debug\\WINApt_Config\\WINApt_Config.ini");
	memset(&st_AppConfig, '\0', sizeof(WINAPT_APPCONFIG));

	GetPrivateProfileString(_T("NetWork"), _T("IP"), NULL, st_AppConfig.st_CfgNetWork.tszIPAddr, sizeof(st_AppConfig.st_CfgNetWork.tszIPAddr), lpszCfgFile);
	GetPrivateProfileString(_T("FileCfg"), _T("DownDir"), NULL, st_AppConfig.st_CfgFile.tszDlDir, sizeof(st_AppConfig.st_CfgFile.tszDlDir), lpszCfgFile);
	GetPrivateProfileString(_T("FileCfg"), _T("DBFile"), NULL, st_AppConfig.st_CfgFile.tszDBFile, sizeof(st_AppConfig.st_CfgFile.tszDBFile), lpszCfgFile);
	st_AppConfig.st_CfgNetWork.nPort = GetPrivateProfileInt(_T("NetWork"), _T("Port"), 0, lpszCfgFile);
	return TRUE;
}
BOOL CNetEngineWINAptAppDlg::WINApt_ParseListLoad(LPCTSTR lpszMsgBuffer)
{
	list<LOGICSQL_SOFTLIST> stl_SoftList;
	if (!WINApt_ProtocolPkt_SearchResponse(lpszMsgBuffer, &stl_SoftList))
	{
		AfxMessageBox(_T("解析数据失败"));
		return FALSE;
	}
	list<LOGICSQL_SOFTLIST>::const_iterator stl_ListIterator = stl_SoftList.begin();
	for (int i = 0; stl_ListIterator != stl_SoftList.end(); stl_ListIterator++, i++)
	{
		TCHAR tszIDNumber[64];
		TCHAR tszDlSize[64];
		TCHAR tszInstallSize[64];

		memset(tszIDNumber, '\0', sizeof(tszIDNumber));
		memset(tszDlSize, '\0', sizeof(tszDlSize));
		memset(tszInstallSize, '\0', sizeof(tszInstallSize));

		_stprintf_s(tszIDNumber, _T("%d"), i);
		m_ListRecord.InsertItem(i, tszIDNumber);
		m_ListRecord.SetItemText(i, 1, stl_ListIterator->tszName);
		m_ListRecord.SetItemText(i, 2, stl_ListIterator->tszFullName);
		m_ListRecord.SetItemText(i, 3, stl_ListIterator->tszVersion);
		m_ListRecord.SetItemText(i, 4, stl_ListIterator->tszAuthor);
		m_ListRecord.SetItemText(i, 5, stl_ListIterator->tszProvider);
		m_ListRecord.SetItemText(i, 6, stl_ListIterator->tszBuildTime);
		m_ListRecord.SetItemText(i, 7, stl_ListIterator->tszContact);
		m_ListRecord.SetItemText(i, 8, stl_ListIterator->tszProjectUrl);

		_stprintf_s(tszDlSize, _T("%lf"), stl_ListIterator->dlDlSize);
		_stprintf_s(tszInstallSize, _T("%lf"), stl_ListIterator->dlInstallSize);
		m_ListRecord.SetItemText(i, 10, tszDlSize);
		m_ListRecord.SetItemText(i, 11, tszInstallSize);

		m_ListRecord.SetItemText(i, 12, stl_ListIterator->tszDlUrl);
		m_ListRecord.SetItemText(i, 13, stl_ListIterator->tszFileMD5);
		m_ListRecord.SetItemText(i, 14, stl_ListIterator->tszDepModule);
		m_ListRecord.SetItemText(i, 15, stl_ListIterator->tszDesInfo);
	}
	return TRUE;
}

void CNetEngineWINAptAppDlg::OnNMRClickList2(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: 在此添加控件通知处理程序代码
	if (-1 != pNMItemActivate->iItem)
	{
		DWORD dwPos = GetMessagePos();
		CPoint m_Point(LOWORD(dwPos), HIWORD(dwPos));


		CMenu m_Menu;
		m_Menu.LoadMenu(IDR_MENU2);
		CMenu *pSt_Popup = m_Menu.GetSubMenu(0);
		pSt_Popup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, m_Point.x, m_Point.y, this);
	}
	*pResult = 0;
}


void CNetEngineWINAptAppDlg::OnUpdate32775(CCmdUI *pCmdUI)
{
	// TODO: 在此添加命令更新用户界面处理程序代码
	int nSelect = m_ListRecord.GetSelectionMark();
	if (-1 == nSelect)
	{
		AfxMessageBox(_T("没有选择要下载的项目"));
		return;
	}
	TCHAR tszFileDir[MAX_PATH];
	TCHAR tszFileName[MAX_PATH];
	TCHAR tszDlFileName[MAX_PATH];
	WINAPT_APPLIST st_AppList;
	
	memset(tszFileDir, '\0', MAX_PATH);
	memset(tszFileName, '\0', MAX_PATH);
	memset(tszDlFileName, '\0', MAX_PATH);
	memset(&st_AppList, '\0', sizeof(WINAPT_APPLIST));

	m_ListRecord.GetItemText(nSelect, 1, st_AppList.tszFileName, MAX_PATH);
	CString m_StrDownUrl = m_ListRecord.GetItemText(nSelect, 12);

	if (!BaseLib_OperatorString_GetFileAndPath(m_StrDownUrl.GetBuffer(), tszFileDir, tszFileName))
	{
		AfxMessageBox(_T("下载路径错误"));
		return;
	}
	_stprintf_s(tszDlFileName, _T("%s%s"), st_AppConfig.st_CfgFile.tszDlDir, tszFileName);

	if (!DownLoad_Http_Create(&st_AppList.xhToken, m_StrDownUrl.GetBuffer(), tszDlFileName))
	{
		AfxMessageBox(_T("下载失败"));
	}

	EnterCriticalSection(&st_Locker);
	stl_ListDlFile.push_back(st_AppList);
	LeaveCriticalSection(&st_Locker);
}

DWORD WINAPI CNetEngineWINAptAppDlg::WINApt_Thread_Download(LPVOID lParam)
{
	CNetEngineWINAptAppDlg *pClass_This = (CNetEngineWINAptAppDlg *)lParam;

	while (pClass_This->bIsRun)
	{
		EnterCriticalSection(&pClass_This->st_Locker);
		list<WINAPT_APPLIST>::const_iterator stl_ListIterator = pClass_This->stl_ListDlFile.begin();
		for (;stl_ListIterator != pClass_This->stl_ListDlFile.end();stl_ListIterator++)
		{
			NETDOWNLOAD_TASKINFO st_TaskInfo;
			memset(&st_TaskInfo, '\0', sizeof(NETDOWNLOAD_TASKINFO));
			if (DownLoad_Http_Query(stl_ListIterator->xhToken, &st_TaskInfo))
			{
				if (ENUM_NETENGINE_DOWNLOAD_STATUS_DOWNLOADDING == st_TaskInfo.en_DownStatus)
				{
					CString m_StrTips;
					m_StrTips.Format(_T("下载文件:%s,文件总大小:%lf,已下载大小:%lf,下载中"), stl_ListIterator->tszFileName, st_TaskInfo.dlTotal, st_TaskInfo.dlNow);
					pClass_This->m_StaticTips.SetWindowText(m_StrTips);
				}
				else if (ENUM_NETENGINE_DOWNLOAD_STATUS_COMPLETE == st_TaskInfo.en_DownStatus)
				{
					CString m_StrTips;
					m_StrTips.Format(_T("下载文件:%s,文件总大小:%d KB,已下载大小:%d KB,下载完成"), stl_ListIterator->tszFileName, (st_TaskInfo.dlTotal * 1024), (st_TaskInfo.dlNow * 1024));
					pClass_This->m_StaticTips.SetWindowText(m_StrTips);
					DownLoad_Http_Delete(stl_ListIterator->xhToken);
					pClass_This->stl_ListDlFile.erase(stl_ListIterator);
					break;
				}
			}
		}
		LeaveCriticalSection(&pClass_This->st_Locker);
		Sleep(1000);
	}
	return 0;
}

void CNetEngineWINAptAppDlg::OnUpdate32774(CCmdUI *pCmdUI)
{
	// TODO: 在此添加命令更新用户界面处理程序代码
	CDlg_About m_DlgAbout;
	m_DlgAbout.DoModal();
}


void CNetEngineWINAptAppDlg::OnBnClickedRadio1()
{
	// TODO: 在此添加控件通知处理程序代码
	m_RadioLocal.SetCheck(BST_CHECKED);
	m_RadioRemote.SetCheck(BST_UNCHECKED);
}


void CNetEngineWINAptAppDlg::OnBnClickedRadio2()
{
	// TODO: 在此添加控件通知处理程序代码
	m_RadioLocal.SetCheck(BST_UNCHECKED);
	m_RadioRemote.SetCheck(BST_CHECKED);
}
